<?php


namespace Muyuxuan\redis\lock;


use Muyuxuan\redis\Other;
/**
 * redis锁
 */
class MredisLock
{
    use Other;
    protected static $defaultKey = 'RedisLocklock';
    /**获取锁
     * @param string $key 键名
     * @param bool $untilGet 是否一直获取
     * @param int $lockExpire 有效期
     * @param int $usleep 睡眠状态
     * @return bool
     */
    public static function getLock(string $key='lock',bool $untilGet=false,int $lockExpire=10,int $usleep = 500000){
        self::setRedis();
        $ke =  'RedisLock'.$key;
        $value = self::$redis->get($ke);
        $lockValue = time()+$lockExpire;
        if(empty($value)){
            self::$redis->setnx($ke,$lockValue);
            return true;
        }else{
            if($value<time()){
                self::$redis->getSet($ke,$lockValue);
                return true;
            }
            if($untilGet===true){
                usleep($usleep);
                return self::gettLock($key,$untilGet,$lockExpire,$usleep);
            }
            return false;
        }
    }
    /**
     * 删除锁
     * @param string $key 键名
     * @return bool
     */
    public static function delLock(string $key='lock'){
        self::setRedis();
        $ke =  'RedisLock'.$key;
        return self::$redis->expire($ke,0);
    }

}